'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';

interface Customer {
  id: number;
  name: string;
  email: string;
  phone: string;
  phone2: string;
  phone2Purpose: string;
  wechat: string;
  wechatPurpose: string;
  qq: string;
  qqPurpose: string;
  whatsapp: string;
  whatsappPurpose: string;
  telegram: string;
  telegramPurpose: string;
  address: string;
  createdAt: string;
  updatedAt: string;
}

interface CustomerNote {
  id: number;
  customerId: number;
  content: string;
  type: string;
  createdBy: string;
  createdAt: string;
}

export default function CustomerDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const [resolvedParams, setResolvedParams] = useState<{ id: string } | null>(null);
  const [customer, setCustomer] = useState<Customer | null>(null);
  const [notes, setNotes] = useState<CustomerNote[]>([]);
  const [loading, setLoading] = useState(true);
  const [notesLoading, setNotesLoading] = useState(false);
  const [editing, setEditing] = useState(false);
  const [showAddNote, setShowAddNote] = useState(false);
  const [newNote, setNewNote] = useState({
    content: '',
    type: 'general',
    createdBy: 'admin'
  });
  const [addingNote, setAddingNote] = useState(false);
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phone: '',
    phone2: '',
    phone2Purpose: '',
    wechat: '',
    wechatPurpose: '',
    qq: '',
    qqPurpose: '',
    whatsapp: '',
    whatsappPurpose: '',
    telegram: '',
    telegramPurpose: '',
    address: ''
  });
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');
  const router = useRouter();

  useEffect(() => {
    async function resolveParams() {
      const resolved = await params;
      setResolvedParams(resolved);
    }
    resolveParams();
  }, [params]);

  useEffect(() => {
    if (resolvedParams) {
      fetchCustomer();
      fetchNotes();
    }
  }, [resolvedParams]);

  const fetchCustomer = async () => {
    if (!resolvedParams) return;
    
    try {
      const response = await fetch(`/api/customers/${resolvedParams.id}`);
      if (!response.ok) {
        throw new Error('获取客户信息失败');
      }
      const data = await response.json();
      setCustomer(data);
      setFormData({
        name: data.name,
        email: data.email,
        phone: data.phone || '',
        phone2: data.phone2 || '',
        phone2Purpose: data.phone2Purpose || '',
        wechat: data.wechat || '',
        wechatPurpose: data.wechatPurpose || '',
        qq: data.qq || '',
        qqPurpose: data.qqPurpose || '',
        whatsapp: data.whatsapp || '',
        whatsappPurpose: data.whatsappPurpose || '',
        telegram: data.telegram || '',
        telegramPurpose: data.telegramPurpose || '',
        address: data.address || ''
      });
    } catch (error) {
      console.error('获取客户详情失败:', error);
      setError('获取客户信息失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchNotes = async () => {
    if (!resolvedParams) return;
    
    setNotesLoading(true);
    try {
      const response = await fetch(`/api/customers/${resolvedParams.id}/notes`);
      if (!response.ok) {
        throw new Error('获取备注失败');
      }
      const data = await response.json();
      setNotes(data);
    } catch (error) {
      console.error('获取客户备注失败:', error);
      setError('获取备注失败');
    } finally {
      setNotesLoading(false);
    }
  };

  const handleAddNote = async () => {
    if (!resolvedParams) return;
    
    setAddingNote(true);
    setError('');
    
    try {
      const response = await fetch(`/api/customers/${resolvedParams.id}/notes`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(newNote),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '添加备注失败');
      }

      const addedNote = await response.json();
      setNotes([...notes, addedNote]);
      setNewNote({ content: '', type: 'general', createdBy: 'admin' });
      setShowAddNote(false);
      
    } catch (error: any) {
      console.error('添加备注失败:', error);
      setError(error.message);
    } finally {
      setAddingNote(false);
    }
  };

  const handleSave = async () => {
    setSaving(true);
    setError('');
    
    try {
      const resolvedParams = React.use(params);
      const response = await fetch(`/api/customers/${resolvedParams.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || '更新失败');
      }

      const updatedCustomer = await response.json();
      setCustomer(updatedCustomer);
      setEditing(false);
      
    } catch (error: any) {
      console.error('更新客户失败:', error);
      setError(error.message);
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async () => {
    if (!confirm('确定要删除这个客户吗？此操作不可撤销。')) {
      return;
    }

    try {
      const response = await fetch(`/api/customers/${params.id}`, {
        method: 'DELETE',
      });

      if (!response.ok) {
        throw new Error('删除失败');
      }

      router.push('/customers');
      
    } catch (error) {
      console.error('删除客户失败:', error);
      setError('删除客户失败');
    }
  };

  if (loading) return <div className="p-8">加载中...</div>;
  if (!customer) return <div className="p-8">客户不存在</div>;

  return (
    <div className="p-8">
      <div className="flex justify-between items-center mb-6">
        <div className="flex items-center space-x-4">
          <Link href="/customers" className="text-gray-600 hover:text-gray-900">
            ← 返回客户列表
          </Link>
          <h1 className="text-3xl font-bold">客户详情</h1>
        </div>
        
        {!editing && (
          <div className="flex space-x-3">
            <button
              onClick={() => setEditing(true)}
              className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
            >
              编辑客户
            </button>
            <button
              onClick={handleDelete}
              className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700"
            >
              删除客户
            </button>
          </div>
        )}
      </div>

      {error && (
        <div className="mb-4 p-4 bg-red-100 border border-red-400 text-red-700 rounded">
          {error}
        </div>
      )}

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div className="md:col-span-2">
          <div className="bg-white rounded-lg shadow p-6">
            <h2 className="text-xl font-semibold mb-4">基本信息</h2>
            
            {editing ? (
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    姓名
                  </label>
                  <input
                    type="text"
                    value={formData.name}
                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    邮箱
                  </label>
                  <input
                    type="email"
                    value={formData.email}
                    onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    电话
                  </label>
                  <input
                    type="tel"
                    value={formData.phone}
                    onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    备用电话
                  </label>
                  <input
                    type="tel"
                    value={formData.phone2}
                    onChange={(e) => setFormData({ ...formData, phone2: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md"
                    placeholder="备用电话号码"
                  />
                  <input
                    type="text"
                    value={formData.phone2Purpose}
                    onChange={(e) => setFormData({ ...formData, phone2Purpose: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md mt-1"
                    placeholder="用途（如：工作电话、家庭电话等）"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    微信
                  </label>
                  <input
                    type="text"
                    value={formData.wechat}
                    onChange={(e) => setFormData({ ...formData, wechat: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md"
                    placeholder="微信号"
                  />
                  <input
                    type="text"
                    value={formData.wechatPurpose}
                    onChange={(e) => setFormData({ ...formData, wechatPurpose: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md mt-1"
                    placeholder="用途"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    QQ
                  </label>
                  <input
                    type="text"
                    value={formData.qq}
                    onChange={(e) => setFormData({ ...formData, qq: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md"
                    placeholder="QQ号"
                  />
                  <input
                    type="text"
                    value={formData.qqPurpose}
                    onChange={(e) => setFormData({ ...formData, qqPurpose: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md mt-1"
                    placeholder="用途"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    WhatsApp
                  </label>
                  <input
                    type="text"
                    value={formData.whatsapp}
                    onChange={(e) => setFormData({ ...formData, whatsapp: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md"
                    placeholder="WhatsApp号码"
                  />
                  <input
                    type="text"
                    value={formData.whatsappPurpose}
                    onChange={(e) => setFormData({ ...formData, whatsappPurpose: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md mt-1"
                    placeholder="用途"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Telegram
                  </label>
                  <input
                    type="text"
                    value={formData.telegram}
                    onChange={(e) => setFormData({ ...formData, telegram: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md"
                    placeholder="Telegram用户名"
                  />
                  <input
                    type="text"
                    value={formData.telegramPurpose}
                    onChange={(e) => setFormData({ ...formData, telegramPurpose: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md mt-1"
                    placeholder="用途"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    地址
                  </label>
                  <textarea
                    value={formData.address}
                    onChange={(e) => setFormData({ ...formData, address: e.target.value })}
                    rows={3}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  />
                </div>

                <div className="flex space-x-3 pt-4">
                  <button
                    onClick={handleSave}
                    disabled={saving}
                    className="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 disabled:bg-gray-400"
                  >
                    {saving ? '保存中...' : '保存'}
                  </button>
                  <button
                    onClick={() => {
                      setEditing(false);
                      setFormData({
                        name: customer.name,
                        email: customer.email,
                        phone: customer.phone || '',
                        address: customer.address || ''
                      });
                      setError('');
                    }}
                    className="px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700"
                  >
                    取消
                  </button>
                </div>
              </div>
            ) : (
              <div className="space-y-4">
                <div className="flex items-center">
                  <div className="flex-shrink-0 h-16 w-16 bg-blue-500 rounded-full flex items-center justify-center text-white text-xl font-bold">
                    {customer.name.charAt(0)}
                  </div>
                  <div className="ml-4">
                    <div className="text-2xl font-bold text-gray-900">{customer.name}</div>
                    <div className="text-sm text-gray-600">客户 ID: {customer.id}</div>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <div className="text-sm text-gray-600">邮箱</div>
                    <div className="text-sm font-medium">{customer.email}</div>
                  </div>
                  <div>
                    <div className="text-sm text-gray-600">电话</div>
                    <div className="text-sm font-medium">{customer.phone || '未填写'}</div>
                  </div>
                </div>

                {customer.phone2 && (
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <div className="text-sm text-gray-600">备用电话</div>
                      <div className="text-sm font-medium">{customer.phone2}</div>
                    </div>
                    <div>
                      <div className="text-sm text-gray-600">用途</div>
                      <div className="text-sm font-medium">{customer.phone2Purpose || '未指定'}</div>
                    </div>
                  </div>
                )}

                {customer.wechat && (
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <div className="text-sm text-gray-600">微信</div>
                      <div className="text-sm font-medium">{customer.wechat}</div>
                    </div>
                    <div>
                      <div className="text-sm text-gray-600">用途</div>
                      <div className="text-sm font-medium">{customer.wechatPurpose || '未指定'}</div>
                    </div>
                  </div>
                )}

                {customer.qq && (
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <div className="text-sm text-gray-600">QQ</div>
                      <div className="text-sm font-medium">{customer.qq}</div>
                    </div>
                    <div>
                      <div className="text-sm text-gray-600">用途</div>
                      <div className="text-sm font-medium">{customer.qqPurpose || '未指定'}</div>
                    </div>
                  </div>
                )}

                {customer.whatsapp && (
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <div className="text-sm text-gray-600">WhatsApp</div>
                      <div className="text-sm font-medium">{customer.whatsapp}</div>
                    </div>
                    <div>
                      <div className="text-sm text-gray-600">用途</div>
                      <div className="text-sm font-medium">{customer.whatsappPurpose || '未指定'}</div>
                    </div>
                  </div>
                )}

                {customer.telegram && (
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <div className="text-sm text-gray-600">Telegram</div>
                      <div className="text-sm font-medium">{customer.telegram}</div>
                    </div>
                    <div>
                      <div className="text-sm text-gray-600">用途</div>
                      <div className="text-sm font-medium">{customer.telegramPurpose || '未指定'}</div>
                    </div>
                  </div>
                )}

                <div>
                  <div className="text-sm text-gray-600">地址</div>
                  <div className="text-sm font-medium">{customer.address || '未填写'}</div>
                </div>

                <div className="grid grid-cols-2 gap-4 pt-4 border-t">
                  <div>
                    <div className="text-sm text-gray-600">创建时间</div>
                    <div className="text-sm font-medium">
                      {new Date(customer.createdAt).toLocaleString('zh-CN')}
                    </div>
                  </div>
                  <div>
                    <div className="text-sm text-gray-600">最后更新</div>
                    <div className="text-sm font-medium">
                      {new Date(customer.updatedAt).toLocaleString('zh-CN')}
                    </div>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>

        <div>
          <div className="bg-white rounded-lg shadow p-6 mb-6">
            <div className="flex justify-between items-center mb-4">
              <h3 className="text-lg font-semibold">客户备注</h3>
              <button
                onClick={() => setShowAddNote(true)}
                className="px-3 py-1 bg-purple-600 text-white text-sm rounded-md hover:bg-purple-700"
              >
                + 添加备注
              </button>
            </div>
            
            {notesLoading ? (
              <div className="text-center text-gray-600">加载备注中...</div>
            ) : notes.length === 0 ? (
              <div className="text-center text-gray-600">暂无备注</div>
            ) : (
              <div className="space-y-3 max-h-64 overflow-y-auto">
                {notes.map((note) => (
                  <div key={note.id} className="p-3 bg-gray-50 rounded-md border">
                    <div className="text-sm text-gray-700">{note.content}</div>
                    <div className="flex justify-between items-center mt-2 text-xs text-gray-500">
                      <span className="bg-blue-100 text-blue-800 px-2 py-1 rounded">
                        {note.type}
                      </span>
                      <span>{new Date(note.createdAt).toLocaleString('zh-CN')}</span>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>

          <div className="bg-white rounded-lg shadow p-6">
            <h3 className="text-lg font-semibold mb-4">快速操作</h3>
            <div className="space-y-3">
              <button className="w-full px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
                查看订单历史
              </button>
              <button className="w-full px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700">
                发送邮件
              </button>
              <button 
                onClick={() => setShowAddNote(true)}
                className="w-full px-4 py-2 bg-purple-600 text-white rounded-md hover:bg-purple-700"
              >
                添加备注
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* 添加备注模态框 */}
      {showAddNote && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-lg shadow-lg w-full max-w-md">
            <div className="p-6">
              <h3 className="text-xl font-semibold mb-4">添加备注</h3>
              
              {error && (
                <div className="mb-4 p-3 bg-red-100 border border-red-400 text-red-700 rounded">
                  {error}
                </div>
              )}

              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    备注内容 *
                  </label>
                  <textarea
                    value={newNote.content}
                    onChange={(e) => setNewNote({ ...newNote, content: e.target.value })}
                    rows={4}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="请输入备注内容"
                    required
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    备注类型
                  </label>
                  <select
                    value={newNote.type}
                    onChange={(e) => setNewNote({ ...newNote, type: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="general">一般备注</option>
                    <option value="service">服务记录</option>
                    <option value="complaint">投诉记录</option>
                    <option value="praise">表扬记录</option>
                    <option value="followup">跟进记录</option>
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    记录人
                  </label>
                  <input
                    type="text"
                    value={newNote.createdBy}
                    onChange={(e) => setNewNote({ ...newNote, createdBy: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="请输入记录人姓名"
                  />
                </div>
              </div>

              <div className="flex space-x-3 pt-6 mt-6 border-t">
                <button
                  onClick={handleAddNote}
                  disabled={addingNote || !newNote.content}
                  className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed"
                >
                  {addingNote ? '添加中...' : '添加备注'}
                </button>
                <button
                  onClick={() => {
                    setShowAddNote(false);
                    setNewNote({ content: '', type: 'general', createdBy: 'admin' });
                    setError('');
                  }}
                  className="px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700"
                >
                  取消
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}